﻿using DataTransfer.Core.Domains;
using DataTransfer.Core.Providers;
using DataTransfer.SDK.Models;
using Platform.Data.Entities.MySql;
using MiniFox.Components;
using MiniFox.Data.EntityFramework;
using MiniFox.Utility;
using DataTransfer.Core.Services;

namespace DataTransfer.Data
{
    [AutoResolve(ExcelImportEngine.COMPONENT_NAME)]
    public class ExcelImporterProvider : EntityDataProvider<PlatformDbContext>, IImportConfigProvider
    {
        public IImporter GetImporter(string name)
        {
            var e = this.CurrentDbContext.DtExcelImport.SingleOrDefault(e => e.Name == name);
            if (e == null) return null;
            var importer = new ExcelImporter
            {
                Name = e.Name,
                DataWriterTypeName = e.DataWriter,
                MaxImportFileSize = e.MaxImportFileSize,
                PreImport = e.PreImport,
                Sheets = e.Sheets.ToJsonObject<ExcelImportSheet[]>(),
            };

            importer.Modules = new Dictionary<string, Type>(e.Modules.ToJsonObject<Dictionary<string, string>>().Select(p =>
            {
                Type type = Type.GetType(p.Value);
                return new KeyValuePair<string, Type>(p.Key, type);
            }));

            return importer;
        }
    }
}
